import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-06-03
 * Time: 7:08
 */
public class Practice {
    public static void main(String[] args) {
        int[] arr={9,1,2,5,7,4,8,6,3,5};
        InsertSort(arr);
        System.out.println(Arrays.toString(arr));
        arr= new int[]{9, 1, 2, 5, 7, 4, 8, 6, 3, 5};
        shellSort(arr);
        System.out.println(Arrays.toString(arr));
        arr= new int[]{9, 1, 2, 5, 7, 4, 8, 6, 3, 5};
        selectSort(arr);
        System.out.println(Arrays.toString(arr));
        arr= new int[]{9,8,7,6,5,4,3,2,1};
        bubble(arr);
        System.out.println(Arrays.toString(arr));
    }
    public  static void InsertSort(int[] arr){
        int len=arr.length;
        for (int i = 1; i <len ; i++) {
            int j=i-1;
            int tmp=arr[i];
            for(;j>=0;j--){
                if(arr[j]>tmp){
                    arr[j+1]=arr[j];
                }
                else{
                    break;
                }
            }
            arr[j+1]=tmp;
        }
    }
    public static void shell(int[] arr,int gap){
        int len=arr.length;
        for (int i = gap; i <len ; i++) {
            int j=i-gap;
            int tmp=arr[i];
            for ( ;j >=0 ; j-=gap) {
                if(arr[j]>tmp){
                    arr[j+gap]=arr[j];
                }else{
                    break;
                }
            }
            arr[j+gap]=tmp;
        }
    }
    public static void shellSort(int[] arr){
        int gap=arr.length;
        while(gap>=1){
            shell(arr,gap);
            gap=gap/2;
        }

    }
    public static void selectSort(int[] arr){
        int len=arr.length;
        for (int i = 0; i < len; i++) {
            int minIndex=i;
            for (int j = i+1; j <len ; j++) {
                if(arr[minIndex]>arr[j]){
                    minIndex=j;
                }
            }
            swap(arr,minIndex,i);
        }
    }
    public static void swap(int[] arr,int i, int j){
        int tmp=arr[i];
        arr[i]=arr[j];
        arr[j]=tmp;
    }
    public static void bubble(int[] arr){
        int len=arr.length;
        for (int i = 0; i < len; i++) {
            boolean flag=true;
            for (int j = 0; j <len-i-1 ; j++) {
                if(arr[j]>arr[j+1]){
                    swap(arr,j,j+1);
                    flag=false;
                }
            }
            if(flag){
                break;
            }
        }
    }
}
